package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.TestTimeInfo;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;

/**
 * 测试网络延迟，获取延迟时间
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class TestNetworkLatency implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 测试时间信息
         */
        private TestTimeInfo timeInfo;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 测试时间信息
         */
        private TestTimeInfo timeInfo;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.TestNetworkLatency.InputMsg.Builder inputMsg =
                CompleteInstruction.TestNetworkLatency.InputMsg.newBuilder();
        TestNetworkLatency.InputMsg thisInput = this.getInput();
        inputMsg.setTimeInfo(thisInput.getTimeInfo().toProto());
        final CompleteInstruction.TestNetworkLatency.Builder builder =
                CompleteInstruction.TestNetworkLatency.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public TestNetworkLatency byteConvertObject(ByteString bytes) {
        CompleteInstruction.TestNetworkLatency testNetworkLatency = null;
        try {
            testNetworkLatency = CompleteInstruction.TestNetworkLatency.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(testNetworkLatency)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        TestNetworkLatency.OutputMsg outputMsg = new TestNetworkLatency.OutputMsg();
        CompleteInstruction.TestNetworkLatency.OutputMsg output = testNetworkLatency.getOutput();
        outputMsg.setTimeInfo(new TestTimeInfo().formProto(output.getTimeInfo()));
        this.setOutput(outputMsg);
        return this;
    }
}

